package com.yk.filedownload.entity;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.concurrent.Executors;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * Project Name:cykfiledownload
 * File Name:DataCarrier
 * Package Name:com.yk.filedownload.entity
 * Date:2017\12\6 0006
 * Author:dengtianjia
 * Description:
 * Copyright (c) 2017, 重庆云凯科技有限公司 All Rights Reserved.
 */
public class DataCarrier implements Serializable {

    /**
     * 文件id
     */
    private String fileId;
    /**
     * 压缩后文件块
     */
    private byte[] compressData;


    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }


    /**
     * 数据压缩
     * @param mateData
     * @throws Exception
     */
    public  void CompressData(byte[] mateData) throws Exception{
        byte[] comappsdata;
        int len = 0;
        Deflater defl = new Deflater(9);
        defl.setInput(mateData);
        defl.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] outputByte = new byte[1024];
        try {
            while (!defl.finished()) {
                len = defl.deflate(outputByte);
                bos.write(outputByte, 0, len);
            }
            defl.end();
        } finally {
            bos.close();
        }
        this.compressData = bos.toByteArray();
    }

    /**
     * 文件解压
     * @return
     */
    public  byte[] UncompressData() throws Exception{
        byte[] output = new byte[0];
        Inflater infl = new Inflater();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            infl.setInput(compressData);
            final byte[] outByte = new byte[1024];
            while (!infl.finished()) {
                // 解压缩并将解压缩后的内容输出到字节输出流bos中
                int len = infl.inflate(outByte);
                if(len == 0){
                    break;
                }
                bos.write(outByte, 0, len);
            }
            output= bos.toByteArray();
        }catch (Exception e){
            output = compressData;
            e.printStackTrace();
        }finally {
            try {
                bos.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        infl.end();
        return output;
    }


    public byte[] getCompressData(){
        return this.compressData;
    }

    public void setCompressData(byte[] compressData) {
        this.compressData = compressData;
    }
}
